<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesBtn">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand" label="按钮">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过 for 循环 嵌套渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

            <!-- <pre>
              {{scope.row}}
            </pre>-->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRolesBtn(scope.row.id)"
            >编辑</el-button>
            <el-button type="text">
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="deleteRolesBtn(scope.row.id)"
              >删除</el-button>
            </el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose"
    >
      <!-- 树形组件
      show-checkbox:显示复选框
      node-key:设置选中节点对应的值
      default-expand-all:是否默认展开所有节点
      :default-checked-keys 设置默认选中项的数组
      ref:设置引用-->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="RightsBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRolesVisible" width="50%" @close="addRolesClosed">
      <el-form
        :model="addRolesForm"
        :rules="addRolesRules"
        ref="addRolesRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editRolesVisible" width="50%" @close="editRolesClosed">
      <el-form
        :model="editRolesForm"
        :rules="editRolesRules"
        ref="editRolesRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      rolesList: [],
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 权限列表数据
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        //   通过label设置树形节点文本展示authName
        label: 'authName',
        // 设置通过children属性展示子节点信息
        children: 'children'
      },
      //设置树形控件中默认选中的内容
      defKeys: [],
      // 保存正在操作的id
      roleId: '',
      // 添加角色对话框显示与隐藏
      addRolesVisible: false,
      addRolesForm: {},
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称！', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述！', trigger: 'blur' }
        ]
      },
      editRolesVisible: false,
      editRolesForm: {},
      editRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称！', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述！', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },

  methods: {
    // 发送权限列表数据请求
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
    },
    // 删除角色权限
    async removeRightById(role, rightId) {
      // 弹窗提示是否要删除
      const confirmResult = await this.$confirm(
        '请问是否要删除该权限',
        '删除提示',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 用户点击确认 confirmResult的结果就为'confirm'
      // 用户点击取消 confirmResult的结果就为catch的错误消息
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除！')
      // 确认删除 发送删除请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 删除成功无需刷新页面 只需要重新将role的children里面重新赋值即可
      this.$message.success(res.meta.msg)
      role.children = res.data
    },
    // 角色分配权限
    async showSetRightDialog(role) {
      //将role.id保存起来以供保存权限时使用
      this.roleId = role.id
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return thsi.$message.error(res.meta.msg)
      // 返回数据正常后 将请求的数据保存在data中
      this.rightsList = res.data
      // 调用getDefKeys进行递归 将三级权限添加到数组中
      this.getDefKeys(role, this.defKeys)
      // 点击分配权限时 对话框显示
      this.setRightDialogVisible = true
    },
    // 渲染角色权限到页面
    getDefKeys(node, arr) {
      //   该函数会获取到当前角色的所有三级权限id并添加到defkeys中
      // 如果当前节点不包括children属性 则表示node为三级权限
      if (!node.children) {
        return arr.push(node.id)
      }
      //   递归调用
      node.children.forEach(item => this.getDefKeys(item, arr))
    },
    // 关闭角色权限对话框
    setRightDialogClose() {
      // 当用户关闭树形对话框 清除掉所有选中状态
      this.deKeys = []
    },
    // 点击权限对话框的确定按钮 发送请求进行更新
    async RightsBtn() {
      // 获取所有全选及半选的内容
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 将数组转换成逗号隔开的字符串
      const idStr = keys.join(',')
      // 发送请求完成更新
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
      // 关闭对话框
      this.setRightDialogVisible = false
    },
    // 添加角色按钮
    addRolesBtn() {
      // 显示添加角色对话框
      this.addRolesVisible = true
    },
    // 关闭添加角色对话框的重置
    addRolesClosed() {
      this.$refs.addRolesRef.resetFields()
    },
    // 添加角色的请求
    async addRoles() {
      // 发送添加角色的请求
      const { data: res } = await this.$http.post('roles', this.addRolesForm)
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // 关闭对话框
      this.addRolesVisible = false
      // 刷新角色权限页面
      this.getRolesList()
    },
    // 编辑角色按钮
    async editRolesBtn(id) {
      // 发送请求获取角色信息
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) return tnis.$message.error(res.meta.msg)
      // 将获取信息渲染到对话框
      this.editRolesForm = res.data
      // 编辑角色对话框显示
      this.editRolesVisible = true
    },
    // 编辑角色对话框关闭时的重置信息动作
    editRolesClosed() {
      this.$refs.editRolesRef.resetFields()
    },
    // 编辑角色对话框确定按钮
    // 点击确定前需要对提交修改的内容进行预验证
    editRoles() {
      this.$refs.editRolesRef.validate(async valid => {
        // 验证不通过 直接return
        if (!valid) return
        // 发送更新的请求
        const { data: res } = await this.$http.put(
          `roles/${this.editRolesForm.roleId}`,
          {
            roleName: this.editRolesForm.roleName,
            roleDesc: this.editRolesForm.roleDesc
          }
        )
        // 刷新页面数据
        this.getRolesList()
        // 关闭编辑角色对话框
        this.editRolesVisible = false
      })
    },
    // 删除角色按钮
    async deleteRolesBtn(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 根据id请求删除
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // 刷新页面
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>